package com.gxkj.spark.helloworld.daos;

import com.gxkj.common.hibernate.HibernateBaseRepositoryImpl;
import com.gxkj.spark.helloworld.entitys.SparkBaseData;
import com.gxkj.spark.helloworld.entitys.SparkSum;

import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Repository
public class SparkSumDaoImpl extends HibernateBaseRepositoryImpl {

    public SparkSum  saveOrUpdate(SparkBaseData entity){

        String hql = "from SparkSum where akey = :akey order by createdAt";
        Map<String ,Object> params = new HashMap<>();
        params.put("akey",entity.getAkey());
        SparkSum dbEntity = this.selectLastOneByHQL(hql,params);
        if(dbEntity != null){
            dbEntity.setUpdatedAt(new Date());
            dbEntity.setAsum(dbEntity.getAsum()+entity.getData());
            this.update(dbEntity);
        }else {
            Date anow  = new Date();
            dbEntity = new SparkSum();
            dbEntity.setAkey(entity.getAkey());
            dbEntity.setAsum(entity.getData());
            dbEntity.setUpdatedAt(anow);
            dbEntity.setCreatedAt(anow);

            this.insert(dbEntity);
        }
        return dbEntity;
    }

}
